<template>
	<n-layout class="h-full w-full">
		<div class="w-1/2 h-1/2 absolute z-50">
			<Transition name="expand">
				<div class="h-full w-full rounded bg-zinc-900" v-show="isCollapse">
					<n-calendar
						class="h-full p-2"
						v-model:value="value"
						:is-date-disabled="isDateDisabled"
						@update:value="handleUpdateValue"
						v-if="0"
					>
						<template #header="{ year, month }">
							<n-flex align="center" justify="space-between">
								<n-text>{{ year }}年{{ month }}月</n-text>
							</n-flex>

						</template>
						<template #default="{ year, month, date}">
							<n-text>{{ year }}-{{ month }}-{{ date }}</n-text>
						</template>
					</n-calendar>
					<n-date-picker v-else v-model:value="range" type="datetimerange" clearable/>
					<pre>{{ JSON.stringify(range) }},,,{{ isCollapse }}</pre>
					<n-button @click="querySignal">查询</n-button>
				</div>
			</Transition>
			<div class="flex flex-nowrap items-center gap-10 ">
				<n-divider/>
				<n-button
					@click="onCollapse"
					:bordered="false"
					size="large"
					class="z-50 transition-all mt-1 duration-300"
					:class="{ 'top-1/2': isCollapse, 'top-0': !isCollapse }"
				>
					<template #icon>
						<n-icon :component="ChevronUp28Regular" v-if="isCollapse"></n-icon>
						<n-icon :component="ChevronDown28Regular" v-else></n-icon>
					</template>
				</n-button>
				<n-divider/>
			</div>
		</div>
		<n-flex class="h-full">
			<n-data-table
				:bordered="false"
				:single-line="false"
				class="h-full w-full"
				ref="tableRef"
				:columns="createCols"
				virtual-scroll-x
				:min-row-height="52"
				:data="data"
				scroll-x="1400"
				flex-height
				virtual-scroll
				:scrollbar-props="{
					trigger: 'none',
				}"
			/>
		</n-flex>
	</n-layout>
</template>

<script setup>
import {addDays, isYesterday} from "date-fns";
import {ChevronDown28Regular, ChevronUp28Regular} from "@vicons/fluent"
import {useMessage} from "naive-ui";
import {ref} from "vue";
import {getDataByDateRange} from "@/db/db.js";

const message = useMessage();
const data = ref([])
const range = ref(null)

const value = ref(addDays(Date.now(), 1).valueOf())
const handleUpdateValue = (_, {year, month, date}) => {
	message.success(`${year}-${month}-${date}`);
}
const isDateDisabled = (timestamp) => {
	return !!isYesterday(timestamp);
}
const isCollapse = ref(0)
const onCollapse = () => {
	isCollapse.value = !isCollapse.value
}
const querySignal = async () => {
	console.time('querySignal')
	console.log(await getDataByDateRange(range.value))
	console.timeEnd('querySignal')
	return
	data.value = []; // 清空数据
	console.time("querySignal");

	const d = await getDataByDateRange(range.value);
	const tempData = new Array(d.length); // 临时数组存储结果
	let pendingItems = d.map((item, index) => ({item, index})); // 待处理队列

	await new Promise((resolve) => {
		const checkItems = () => {
			const stillPending = []; // 本轮仍未处理的项
			pendingItems.forEach(({item, index}) => {
				if (item.readyState === 'done') {
					// 处理完成项
					const result = item.result;
					tempData[index] = {
						"序号": index + 1, // 使用原始索引作为序号
						...Object.fromEntries( // 更高效的对象转换
							result.parsedData.map(it => [it.label, it.value])
						)
					};
				} else {
					stillPending.push({item, index}); // 继续等待
				}
			});

			// 判断是否全部完成
			if (stillPending.length === 0) {
				resolve();
			} else {
				pendingItems = stillPending;
				setTimeout(checkItems, 1000); // 下一轮检查
			}
		};
		checkItems(); // 开始处理
	});

	data.value = tempData; // 一次性赋值
	console.timeEnd("querySignal");
};

// 创建标的列, 由生成数据的首行keys决定
const createCols = computed(() => {
	if (data.value.length === 0) return []
	// 提取首个数据的key当作列标题并添加序号列
	const keys = Object.keys({"序号": 1, ...data.value[0]})
	console.log(keys)

	return keys.sort((a) => a === "序号" ? -1 : 1).map((col, i) => {
		return {
			title: col,
			key: col,
			width: 200,
			fixed: i <= 1 ? "left" : i >= keys.length - 1 ? "right" : void 0
		}
	})
})


</script>

<style scoped>
.expand-enter-active,
.expand-leave-active {
	transition: max-height 0.75s ease-in-out,
	opacity 0.75s ease-in-out,
	bottom 0.75s ease-in-out;
	overflow: hidden;
}

.expand-enter-from,
.expand-leave-to {
	max-height: 0;
	opacity: 0;
	padding: 0;
}

.expand-enter-to,
.expand-leave-from {
	opacity: 1;
	max-height: 100%;
}
</style>